import React, { useState } from 'react';
import { Drawer, Form, Select, Button, Alert, message } from 'antd';
import { connect, useDispatch } from 'umi';
import { InfoCircleOutlined } from '@ant-design/icons';
const { Option } = Select;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const AddAuth = props => {
  const { defaultSelectedKeys, checkTreeKey, getRoleListData, handleCloseDrawer } = props;
  const [form] = Form.useForm();

  const dispatch = useDispatch();
  const [dataRoleKey, setDataRoleKey] = useState([]);
  const [dataRoleName, setDataRoleName] = useState([]);
  const roleCodeOptions = getRoleListData.length > 0 ? getRoleListData.map(item => <Option key={item.roleId}>{item.roleCode}</Option>) : null;
  const roleNameOptions = getRoleListData.length > 0 ? getRoleListData.map(item => <Option value={item.roleName}>{item.roleName}</Option>) : null;

  const handleSearch = (value, type) => {
    if (type === "code") {
      const newRoleCodeList = getRoleListData.filter(item => item.roleCode.includes(value));
      setDataRoleKey(newRoleCodeList)
    } else {
      const newRoleNameList = getRoleListData.filter(item => item.roleName.includes(value));
      setDataRoleName(newRoleNameList)
    }
  }

  const handleChange = (value, type) => {
    if (type === "code") {
      const newRoleCodeList = getRoleListData.filter(item => item.roleId === Number(value));
      setDataRoleName(newRoleCodeList)
      form.setFieldsValue({
        roleNameKey: newRoleCodeList[0].roleName,
      });
    } else {
      const newRoleNameList = getRoleListData.filter(item => item.roleName === value);
      setDataRoleKey(newRoleNameList)
      form.setFieldsValue({
        roleId: newRoleNameList[0].roleId,
      });
    }
  }

  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const { roleId } = values
      const resourceId = checkTreeKey.length > 0 ? Number(checkTreeKey.toString()) : Number(defaultSelectedKeys.toString());
      dispatch({
        type: 'resModel/addRoleRes',
        payload: { roleId: Number(roleId), resourceId }
      }).then(res => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success("授权成功！");
          handleCloseDrawer(true);
        } else {
          message.error(errMsg);
        }
      })
    });
  }

  return (
    <Drawer
      title="授权"
      width={600}
      placement="right"
      visible
      onClose={handleCloseDrawer}
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button style={{ marginRight: 8 }} onClick={handleCloseDrawer}>取消</Button>
          <Button type="primary" onClick={handleSubmit}>确定</Button>
        </div>
      )}
    >
      <Alert message="请输入角色编码或角色名称，都将自动带出角信息" type="info" showIcon style={{ marginBottom: 25 }} />
      <Form {...layout} form={form}>
        <Form.Item
          label="角色编码"
          name="roleId"
          rules={[{ required: true, message: '请输入角色编码!' }]}
        >
          <Select placeholder="请输入角色编码"
            showSearch
            defaultActiveFirstOption={false}
            filterOption={false}
            onSearch={(value) => handleSearch(value, "code")}
            onChange={(value) => handleChange(value, "code")}
          >
            {
              dataRoleKey.length > 0 ?
              dataRoleKey.map(item => <Option key={item.roleId}>{item.roleCode}</Option>)
              :roleCodeOptions
            }
          </Select>
        </Form.Item>

        <Form.Item
          label="角色名称"
          name="roleNameKey"
          tooltip={{
            title: '请输入需要授权的角色名称',
            icon: <InfoCircleOutlined />,
          }}
          rules={[{ required: true, message: '请输入角色名称!' }]}
        >
          <Select placeholder="请输入角色名称"
            showSearch
            defaultActiveFirstOption={false}
            filterOption={false}
            onSearch={handleSearch}
            onChange={handleChange}
          >
            {
              dataRoleName.length > 0 ?
              dataRoleName.map(item => <Option value={item.roleName}>{item.roleName}</Option>)
              :roleNameOptions
            }
          </Select>
        </Form.Item>
      </Form>
    </Drawer>
  )
}

export default connect(state => state)(AddAuth);